package com.g17.virtualpetbackend.service;

import com.g17.virtualpetbackend.entity.Test;
import com.g17.virtualpetbackend.repo.TestRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class TestService {

    @Resource
    private TestRepository testRepository;

    private static Logger logger = LoggerFactory.getLogger(TestService.class);

    public List<Test> getAllTests() {
        return testRepository.findAll();
    }

    public Test getTestById(Long id) {
        return testRepository.getTestById(id);
    }

    public Test createTest(Map<String, String> testData) {
        String question = testData.get("question");
        String choice1 = testData.get("choice1");
        String choice2 = testData.get("choice2");
        String choice3 = testData.get("choice3");
        String choice4 = testData.get("choice4");
        String answer = testData.get("answer");
        Float point = Float.valueOf(testData.get("point"));
        return testRepository.createTest(question, choice1, choice2, choice3, choice4, answer, point);
    }

    public Test updateTest(Map<String, String> testData) {
        Long id = Long.parseLong(testData.get("id"));
        String question = testData.get("question");
        String choice1 = testData.get("choice1");
        String choice2 = testData.get("choice2");
        String choice3 = testData.get("choice3");
        String choice4 = testData.get("choice4");
        String answer = testData.get("answer");
        String point = testData.get("point");
        return testRepository.updateTest(id, question, choice1, choice2, choice3, choice4, answer, point);
    }

    public Long deleteTest(Long id) {
        testRepository.deleteTestById(id);
        Test test = testRepository.getTestById(id);
        if (test == null) {
            return id;
        }
        return (long) -1;
    }

    public List<Test> getTestByPaperId(Long paperId) {
        return testRepository.findTestByPaperId(paperId);
    }

    public Float calculateScore(String[] questionId, String[] questionChosen) {
        Test test = new Test();
        Float score = 0.0F;
        for (int i = 0; i < questionId.length; i++) {
            if (testRepository.findById(Long.valueOf(questionId[i])).isPresent()) {
                test = testRepository.findById(Long.valueOf(questionId[i])).get();
            }
            if (questionChosen[i].toCharArray()[0] == test.getAnswer().charAt(0)) {
                score += test.getPoint();
            }
        }
        return score;
    }
}
